import os
import sys


class Config:
    def __init__(self) -> None:
        self.tickrate = 20
        self.left = 0
        self.top = 0
        self.width = 300
        self.height = 200
        self.title = "无标题 - 记事本"
        self.mode = 0
        self.startup = 0
        self.filename = ""
        self.__dic = {
            "刷新频率": "tickrate",
            "左": "left",
            "顶": "top",
            "宽": "width",
            "高": "height",
            "窗口标题": "title",
            "模式启动": "mode",
            "自启动": "startup",
            "文件路径": "filename",
        }

    def __translate(self, z):
        if z in self.__dic:
            return self.__dic[z]
        else:
            return None

    def __set(self, text):
        if not text.startswith("窗口标题="):
            li = text.split("=")
        else:
            li = ["窗口标题", text[5:]]
        if text.startswith("#") or len(li) != 2:
            return
        if self.__translate(li[0]):
            self.__dict__[self.__translate(li[0])] = li[1]

    @staticmethod
    def __str_int(stri, default=0, min=0, max=9999):
        if isinstance(stri, int):
            num = stri
        else:
            num = int("".join(filter(lambda x: x.isdigit(), stri)))
        if min <= num <= max:
            return num
        else:
            return default

    def __purify(self):
        self.tickrate = self.__str_int(self.tickrate, default=20, min=1, max=128)
        self.left = self.__str_int(self.left)
        self.top = self.__str_int(self.top)
        self.width = self.__str_int(self.width)
        self.height = self.__str_int(self.height)
        self.mode = self.__str_int(self.mode, 0, 0, 2)
        self.startup = self.__str_int(self.startup, 0, 0, 1)

    def __update_from_file(self):
        exe_name = os.path.basename(sys.argv[0])
        txt_name = os.path.splitext(exe_name)[0] + ".txt"
        if txt_name in os.listdir():
            with open(txt_name, encoding="utf-8") as profile:
                for i in range(20):
                    line = profile.readline().rstrip("\n")
                    self.__set(line)
                self.__purify()
                self.filename = ""
            profile.close()

    def __update_from_args(self):
        sa = sys.argv
        if len(sa) == 1:
            return
        for i in sa[1:]:
            self.__set(i)
        self.__purify()

    def __update_from_args_filename(self):
        sa = sys.argv
        if len(sa) == 1:
            return
        if os.path.isfile(sa[-1]):
            self.filename = sa[-1]

    def update(self):
        self.__update_from_args()
        self.__update_from_file()
        self.__update_from_args_filename()

    def __create_txt_config(self):
        content = """#刷新频率(时间格式，单位毫秒)
刷新频率=20

#模式一数据(数字格式，大于等于零的整数)
左=0
顶=0
宽=300
高=200

#模式二数据(文本格式，非空，非空格)
窗口标题=无标题1 - 记事本

#模式启动(0:不启动/1:模式一/2:模式二)
模式启动=0

#随Windows系统启动(0:不启动/1:启动)
自启动=0"""
        exe_name = os.path.basename(sys.argv[0])
        txt_name = os.path.splitext(exe_name)[0] + ".txt"

        profile = open(txt_name, "w", encoding="utf-8")
        profile.write(content)
        profile.close()

    def create(self):
        self.__create_txt_config()
